package com.bdqn.service;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.mapper.SysGeneratorMapper;
import com.bdqn.pojo.GenConfig;
import com.bdqn.util.GeneratorUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器
 *
 * @author lilibo
 * @date 2019/2/1
 */
@Service
public class SysGeneratorServiceImpl extends ServiceImpl<SysGeneratorMapper, GenConfig> implements SysGeneratorService {

	@Resource
	private SysGeneratorMapper sysGeneratorMapper;

	/**
	 * 分页查询表
	 *
	 * @param tableName 查询条件
	 * @return
	 */
	@Override
	public IPage<List<Map<String, Object>>> queryPage(Page page, String tableName) {
		return sysGeneratorMapper.queryList(page, tableName);
	}

	/**
	 * 生成代码
	 *
	 * @param genConfig 生成配置
	 * @return
	 */
	@Override
	public boolean generatorProjectModule(GenConfig genConfig) {
		// 生成工程
		GeneratorUtil.generatorProjectModule(genConfig);
		return true;
	}

	/**
	 * 生成代码
	 *
	 * @param genConfig 生成配置
	 * @return
	 */
	@Override
	public boolean generatorCodeLocal(GenConfig genConfig) {
		// 查询表信息
		Map<String, String> table = queryTable(genConfig.getTableName());
		// 查询列信息
		List<Map<String, String>> columns = queryColumns(genConfig.getTableName());
		// 生成代码
		GeneratorUtil.generatorCodeLocal(genConfig, table, columns);
		return true;
	}

	/**
	 * 生成代码
	 *
	 * @param genConfig 生成配置
	 * @return
	 */
	@Override
	public byte[] generatorCode(GenConfig genConfig) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);

		// 查询表信息
		Map<String, String> table = queryTable(genConfig.getTableName());
		// 查询列信息
		List<Map<String, String>> columns = queryColumns(genConfig.getTableName());
		// 生成代码
		GeneratorUtil.generatorCode(genConfig, table, columns, zip);
		IoUtil.close(zip);
		return outputStream.toByteArray();
	}

	private Map<String, String> queryTable(String tableName) {
		return sysGeneratorMapper.queryTable(tableName);
	}

	private List<Map<String, String>> queryColumns(String tableName) {
		return sysGeneratorMapper.queryColumns(tableName);
	}

}
